<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { useFs } from '@fast-crud/fast-crud';

import { UserConfig } from '#/api';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions, frontRules } from '../data/password';

defineOptions({
  name: 'SafetyPasswordModal',
  inheritAttrs: false,
});

const { createMessage } = useMessage();
const formRef = ref();
const userStore = useUserStore();
const { crudBinding, appendCrudOptions } = useFs({ createCrudOptions });

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    const data = userStore.userInfo;

    formRef.value.setFormData({ id: data?.id }, { mergeForm: false });
  },
  onConfirm: handleSubmit,
});

onMounted(async () => {
  const addFormOptions = await getValidateRulesByFs({
    Api: UserConfig.UpdatePassword,
    mode: ActionEnum.ADD,
    customRules: frontRules(formRef),
  });
  appendCrudOptions({ ...addFormOptions });
});

async function handleSubmit() {
  await formRef.value.submit();

  createMessage.success($t(`common.tips.editSuccess`));
  modalApi.close();
}

defineExpose(modalApi);
</script>

<template>
  <Modal title="修改密码">
    <div class="p-4">
      <FsForm ref="formRef" v-bind="crudBinding.addForm" />
    </div>
  </Modal>
</template>
